package com.andreas.shop.serviceImp;

import com.andreas.shop.common.Constant;
import com.andreas.shop.dao.CartMapper;
import com.andreas.shop.dao.OrderItemMapper;
import com.andreas.shop.dao.OrderMapper;
import com.andreas.shop.dao.ProductMapper;
import com.andreas.shop.exception.ShopBussinessException;
import com.andreas.shop.exception.ShopException;
import com.andreas.shop.filter.UserFilter;
import com.andreas.shop.pojo.Order;
import com.andreas.shop.pojo.OrderItem;
import com.andreas.shop.pojo.Product;
import com.andreas.shop.pojo.request.CreateOrderRequest;
import com.andreas.shop.pojo.vo.CartVO;
import com.andreas.shop.pojo.vo.OrderItemVO;
import com.andreas.shop.pojo.vo.OrderVO;
import com.andreas.shop.service.CartService;
import com.andreas.shop.service.OrderService;
import com.andreas.shop.service.UserService;
import com.andreas.shop.utils.OrderCodeFactory;
import com.andreas.shop.utils.QRCodeGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.zxing.WriterException;
import org.apache.logging.log4j.core.util.CloseShieldOutputStream;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Filter;

/**
 * @Author andreaszhou
 * @ClassName OrderServiceImpl
 * @Description Order Service实现层
 * @date 2021/2/2 8:47
 * @Version 1.0
 */
@Service
//数据库事务
@Transactional(rollbackFor = Exception.class)
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private CartService cartServiceImp;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private CartMapper cartMapper;
    @Resource
    private OrderItemMapper orderItemMapper;
    @Resource
    private UserService userServiceImp;

    @Value("${file.upload.ip}")
    String ip;

    @Override
    public String createOrder(CreateOrderRequest createOrderRequest) throws ShopBussinessException {
        /*
         * 在这里我们开始书写创建订单的接口，这个接口是比较的复杂，相应大家一定会收获很多。
         * */

        //1.首先获取用户的信息
        Integer userId = UserFilter.current_user.getId();
        //2.根据用户的id查找到所有的购物车的数据
        List<CartVO> cartVOS = cartServiceImp.listCart(userId);
        //3.选出勾选就是selected的购物车的商品
        ArrayList<CartVO> cartVOSTemp = new ArrayList<>();
        for (int i = 0; i < cartVOS.size(); i++) {
            CartVO cartVO = cartVOS.get(i);
            if (cartVO.getSelected().equals(Constant.Cart.CHECKED)) {
                cartVOSTemp.add(cartVO);
            }
        }
        cartVOS = cartVOSTemp;
        //4.如果购物车的勾选为空，报错
        if (cartVOS == null) {
            throw new ShopBussinessException(ShopException.CART_EMPTY);
        }
        //5.判断商品是否存在、上下架状态、库存
        isValidProductSaleStatusStock(cartVOS);
        //6.把购物车对象转为订单item对象 // 将所有的CartVOS转换为OrderItem
        List<OrderItem> orderItems = transferCartVOSToOrderItem(cartVOS);
        //7.扣库存
        for (int i = 0; i < orderItems.size(); i++) {
            OrderItem orderItem = orderItems.get(i);
            Product product = productMapper.selectByPrimaryKey(orderItem.getProductId());
            int stock = product.getStock() - orderItem.getQuantity();
            if (stock < 0) {
                throw new ShopBussinessException(ShopException.NOT_ENOUGH);
            }
            product.setStock(stock);
            int temp = productMapper.updateByPrimaryKeySelective(product);
            if (temp == 0) {
                throw new ShopBussinessException(ShopException.UPDATE_FAILED);
            }
        }
        //8.把购物车中的已勾选商品删除
        cleanCart(cartVOS);
        //9.生成订单
        Order order = new Order();
        //10.生成订单号，有独立的规则
        String orderCode = OrderCodeFactory.getOrderCode(Long.valueOf(userId));
        //将每一个数据都保存在order订单中
        order.setOrderNo(orderCode);
        order.setUserId(userId);
        order.setTotalPrice(totalPrice(orderItems));
        order.setReceiverName(createOrderRequest.getReceiverName());
        order.setReceiverMobile(createOrderRequest.getReceiverMobile());
        order.setReceiverAddress(createOrderRequest.getReceiverAddress());
        order.setOrderStatus(Constant.OrderStatusEnum.NOT_PAID.getCode());
        order.setPostage(0);
        order.setPaymentType(1);
        // 插入到order表中
        int i = orderMapper.insertSelective(order);
        if (i == 0) {
            throw new ShopBussinessException(ShopException.INSERT_FAILED);
        }

        //11.循环保存每个商品到order_item表
        for (int j = 0; j < orderItems.size(); j++) {
            OrderItem orderItem = orderItems.get(j);
            orderItem.setOrderNo(order.getOrderNo());
            orderItemMapper.insertSelective(orderItem);
        }
        return order.getOrderNo();
    }


    /*计算总价格*/
    private Integer totalPrice(List<OrderItem> orderItems) {
        Integer totalPrice = 0;
        for (int i = 0; i < orderItems.size(); i++) {
            OrderItem orderItem = orderItems.get(i);
            totalPrice += orderItem.getTotalPrice();
        }
        return totalPrice;
    }

    private void cleanCart(List<CartVO> cartVOS) throws ShopBussinessException {
        for (int i = 0; i < cartVOS.size(); i++) {
            CartVO cartVO = cartVOS.get(i);
            int temp = cartMapper.deleteByPrimaryKey(cartVO.getId());
            if (temp == 0) {
                throw new ShopBussinessException(ShopException.DELETE_FAILED);
            }
        }
    }

    /*把购物车对象转为订单item对象*/
    private List<OrderItem> transferCartVOSToOrderItem(List<CartVO> cartVOS) {
        List<OrderItem> orderItemList = new ArrayList<>();
        for (int i = 0; i < cartVOS.size(); i++) {
            CartVO cartVO = cartVOS.get(i);
            OrderItem orderItem = new OrderItem();
            orderItem.setProductId(cartVO.getProductId());
            //记录商品快照信息
            orderItem.setProductName(cartVO.getProductName());
            orderItem.setProductImg(cartVO.getProductImage());
            orderItem.setUnitPrice(cartVO.getPrice());
            orderItem.setQuantity(cartVO.getQuantity());
            orderItem.setTotalPrice(cartVO.getTotalPrice());
            orderItemList.add(orderItem);
        }
        return orderItemList;
    }

    /*判断商品是否存在、上下架状态、库存*/
    private void isValidProductSaleStatusStock(List<CartVO> cartVOS) throws ShopBussinessException {
        for (int i = 0; i < cartVOS.size(); i++) {
            CartVO cartVO = cartVOS.get(i);
            Product product = productMapper.selectByPrimaryKey(cartVO.getProductId());
            //判断商品是否存在，商品是否上架
            if (product == null || product.getStatus().equals(Constant.SaleStatus.NOT_SALT)) {
                throw new ShopBussinessException(ShopException.NOT_SALE);
            }
            //判断商品库存
            if (cartVO.getQuantity() > product.getStock()) {
                throw new ShopBussinessException(ShopException.NOT_STOCK);
            }
        }
    }


    @Override
    public OrderVO orderDetail(String orderNo) throws ShopBussinessException {
        Order order = orderMapper.selectByOrderNum(orderNo);
        //订单不存在，则报错
        if (order == null) {
            throw new ShopBussinessException(ShopException.NO_ORDER);
        }
        //订单存在，需要判断所属
        Integer userId = UserFilter.current_user.getId();
        if (!order.getUserId().equals(userId)) {
            throw new ShopBussinessException(ShopException.NOT_YOUR_ORDER);
        }
        //下面我们要做的就是返回OrderVO   因此在这里我们写一个方法，这个方法可以用来返回OrderVO
        OrderVO orderVO = getOrderVO(order);
        return orderVO;
    }

    private OrderVO getOrderVO(Order order) throws ShopBussinessException {
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order, orderVO);
        List<OrderItem> orderItems = orderItemMapper.selectByOrderNum(order.getOrderNo());
        ArrayList<OrderItemVO> orderItemVOS = new ArrayList<>();
        for (int i = 0; i < orderItems.size(); i++) {
            OrderItem orderItem = orderItems.get(i);
            OrderItemVO orderItemVO = new OrderItemVO();
            BeanUtils.copyProperties(orderItem, orderItemVO);
            orderItemVOS.add(orderItemVO);
        }
        orderVO.setOrderItemVOList(orderItemVOS);
        String statusName = Constant.OrderStatusEnum.codeOf(orderVO.getOrderStatus()).getValue();
        orderVO.setOrderStatusName(statusName);
        return orderVO;
    }

    @Override
    public PageInfo orderList(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Integer userId = UserFilter.current_user.getId();
        List<Order> orders = orderMapper.selectByUserId(userId);
        PageInfo pageInfo = new PageInfo(orders);
        //将我们的orders转换为对应orderVO
        List<OrderVO> orderVOS = transferOrderToOrderVO(orders);
        pageInfo.setList(orderVOS);
        return pageInfo;
    }

    private List<OrderVO> transferOrderToOrderVO(List<Order> orders) {
        ArrayList<OrderVO> orderVOS = new ArrayList<>();
        for (int i = 0; i < orders.size(); i++) {
            Order order = orders.get(i);
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);
            String orderNo = order.getOrderNo();
            List<OrderItem> orderItems = orderItemMapper.selectByOrderNum(orderNo);
            ArrayList<OrderItemVO> orderItemVOS = new ArrayList<>();
            for (int j = 0; j < orderItems.size(); j++) {
                OrderItem orderItem = orderItems.get(j);
                OrderItemVO orderItemVO = new OrderItemVO();
                BeanUtils.copyProperties(orderItem, orderItemVO);
                orderItemVOS.add(orderItemVO);
            }
            orderVO.setOrderItemVOList(orderItemVOS);
            orderVOS.add(orderVO);
        }
        return orderVOS;
    }

    /*注意这个是取消订单，不是删除订单*/
    @Override
    public void cancelOrder(String orderNo) throws ShopBussinessException {
        Order order = orderMapper.selectByOrderNum(orderNo);
        //判断订单是否存在
        if (order == null) {
            throw new ShopBussinessException(ShopException.NO_ORDER);
        }
        //判断该订单是不是属于你
        if (order.getUserId().equals(UserFilter.current_user.getId())) {
            throw new ShopBussinessException(ShopException.NOT_YOUR_ORDER);
        }
        //判断订单状态是不是未付款的状态，如果不是未付款的状态，那么就抛出异常
        if (!order.getOrderStatus().equals(Constant.OrderStatusEnum.NOT_PAID.getCode())){
            throw new ShopBussinessException(ShopException.WRONG_ORDER_STATUS);
        }
        order.setOrderStatus(Constant.OrderStatusEnum.NOT_PAID.getCode());
        order.setEndTime(new Date());
        orderMapper.updateByPrimaryKeySelective(order);
    }

    @Override
    public String qrcode(String orderNo) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        String address = ip + ":" + request.getLocalPort();
        String payUrl = "http://" + address + "/pay?orderNo=" + orderNo;
        try {
            QRCodeGenerator
                    .generateQRCodeImage(payUrl, 350, 350,
                            Constant.FILE_UPLOAD_DIR + orderNo + ".png");
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String pngAddress = "http://" + address + "/images/" + orderNo + ".png";
        return pngAddress;
    }

    @Override
    public void pay(String orderNo) throws ShopBussinessException {
        Order order = orderMapper.selectByOrderNum(orderNo);
        //查不到订单，报错
        if (order == null) {
            throw new ShopBussinessException(ShopException.NO_ORDER);
        }
        //判断订单是不是为支付，如果未支付的时候，我们就可以选择支付，如果是没有未支付的状态，那么就会报错。
        //所以我们在这里一定要为支付的状态
        if (order.getOrderStatus() == Constant.OrderStatusEnum.NOT_PAID.getCode()) {
            order.setOrderStatus(Constant.OrderStatusEnum.PAID.getCode());
            order.setPayTime(new Date());
            int i = orderMapper.updateByPrimaryKeySelective(order);
            if (i==0){
                throw new ShopBussinessException(ShopException.UPDATE_FAILED);
            }
        } else {
            throw new ShopBussinessException(ShopException.WRONG_ORDER_STATUS);
        }
    }

    @Override
    public PageInfo listForAdmin(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Order> orderList = orderMapper.selectAllForAdmin();
        List<OrderVO> orderVOList = transferOrderToOrderVO(orderList);
        PageInfo pageInfo = new PageInfo<>(orderList);
        pageInfo.setList(orderVOList);
        return pageInfo;
    }

    @Override
    public void delivered(String orderNo) throws ShopBussinessException {
        Order order = orderMapper.selectByOrderNum(orderNo);
        if (order==null){
            throw new ShopBussinessException(ShopException.NO_ORDER);
        }
        if (!order.getOrderStatus().equals(Constant.OrderStatusEnum.PAID.getCode())){
            throw new ShopBussinessException(ShopException.WRONG_ORDER_STATUS);
        }
        order.setOrderStatus(Constant.OrderStatusEnum.PAID.getCode());
        order.setDeliveryTime(new Date());
        int i = orderMapper.updateByPrimaryKeySelective(order);
        if (i==0){
            throw new ShopBussinessException(ShopException.UPDATE_FAILED);
        }
    }

    @Override
    public void finish(String orderNo) throws ShopBussinessException {
        Order order = orderMapper.selectByOrderNum(orderNo);
        //查不到订单，报错
        if (order == null) {
            throw new ShopBussinessException(ShopException.NO_ORDER);
        }
        //如果是普通用户，就要校验订单的所属
        if (!userServiceImp.isAdmin(UserFilter.current_user) && !order.getUserId()
                .equals(UserFilter.current_user.getId())) {
            throw new ShopBussinessException(ShopException.NOT_YOUR_ORDER);
        }
        //发货后可以完结订单
        if (!order.getOrderStatus().equals(Constant.OrderStatusEnum.DELIVERED.getCode())){
            throw new ShopBussinessException(ShopException.WRONG_ORDER_STATUS);
        }
        order.setOrderStatus(Constant.OrderStatusEnum.FINISHED.getCode());
        order.setEndTime(new Date());
        int i = orderMapper.updateByPrimaryKeySelective(order);
        if (i==0){
            throw new ShopBussinessException(ShopException.UPDATE_FAILED);
        }
    }
}
